package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.VideoFilterAdapter;
import flc.ast.bean.MyVideoFilterBean;
import flc.ast.databinding.ActivityVideoFilterBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoFilterActivity extends BaseAc<ActivityVideoFilterBinding> {

    public static String videoPath;
    private boolean isExperience = false;
    private long videoLength;
    private String oldPath = "";
    private VideoFilterAdapter filterAdapter;
    private int oldPosition = 0;
    private boolean isFilter = false;
    private String filter = "";
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoLeftText.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_filter;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoFilterBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivVideoFilterExperience.setOnClickListener(this);
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivVideoFilterSave.setOnClickListener(this);

        mDataBinding.rvVideoFilterList.setLayoutManager(new GridLayoutManager(mContext, 6));
        filterAdapter = new VideoFilterAdapter();
        mDataBinding.rvVideoFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoPlay://播放/暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivVideoFilterExperience://立即体验
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
                    mDataBinding.videoView.pause();
                }
                if (TextUtils.isEmpty(filter)) {
                    isFilter = false;
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.setVideoPath(videoPath);
                    mDataBinding.videoView.seekTo(1);
                    mDataBinding.videoView.start();
                } else {
                    //添加滤镜
                    filterVideo();
                }
                break;
            case R.id.ivVideoFilterSave://导出
                if (!isExperience) {
                    ToastUtils.showShort(getString(R.string.please_filter_video));
                    return;
                } else {
                    if (mDataBinding.videoView.isPlaying()) {
                        mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
                        mDataBinding.videoView.pause();
                        stopTime();
                    }
                    saveVideo();
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        filterAdapter.getItem(oldPosition).setSelect(false);
        filterAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        filterAdapter.getItem(position).setSelect(true);
        filterAdapter.notifyItemChanged(position);
        //设置滤镜
        if (isFilter) return;
        filter = filterAdapter.getItem(position).getFilter();
        isFilter = true;
        //重置路径 --避免叠加
        videoPath = oldPath;
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        oldPath = videoPath;
        setPlayer();
        List<MyVideoFilterBean> listFilter = new ArrayList<>();
        listFilter.add(new MyVideoFilterBean("", getString(R.string.filter_text1), "#00000000", R.drawable.kj_13, R.drawable.lj_1, true));
        listFilter.add(new MyVideoFilterBean("lutyuv='u=128:v=128'", getString(R.string.filter_text2), "#323333", R.drawable.lj_2, R.drawable.kj_11, false));
        listFilter.add(new MyVideoFilterBean("hue='h=60:s=-3'", getString(R.string.filter_text3), "#C376F3", R.drawable.lj_3, R.drawable.kj_9, false));
        listFilter.add(new MyVideoFilterBean("lutyuv='y=maxval+minval-val:u=maxval+minval-val:v=maxval+minval-val'", getString(R.string.filter_text4), "#6F7171", R.drawable.lj_4, R.drawable.kj_12, false));
        listFilter.add(new MyVideoFilterBean("lutyuv=y=negval", getString(R.string.filter_text5), "#505151", R.drawable.lj_5, R.drawable.kj_8, false));
        listFilter.add(new MyVideoFilterBean("lutyuv='u=128:v=128'", getString(R.string.filter_text7), "#999999", R.drawable.lj_6, R.drawable.kj_10, false));
        filterAdapter.setList(listFilter);
    }

    //添加滤镜
    private void filterVideo() {
        EpVideo epVideo = new EpVideo(videoPath);
        epVideo.addFilter(filter);
        String path = FileUtil.generateFilePath(Content.myTemp, ".mp4", videoPath);
        EpEditor.OutputOption outputOption = new EpEditor.OutputOption(path);
        EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        isFilter = false;
                        isExperience = true;
                        videoPath = path;
                        //设置播放器
                        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                        mDataBinding.videoView.setVideoPath(videoPath);
                        mDataBinding.videoView.seekTo(1);
                        mDataBinding.videoView.start();
                    }
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        isFilter = false;
                        ToastUtils.showShort(R.string.add_filter_def);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                float v = progress * 100;
                if (v < 0) {
                    v = 0;
                } else if (v > 100) {
                    v = 100;
                }
                showDialog(getString(R.string.add_filter_ing) + new DecimalFormat("#.0").format(v) + "%");
            }
        });
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);
                        String filePath = FileUtil.generateFilePath(Content.myRecord, "." + FileUtils.getFileExtension(videoPath));
                        FileUtils.copy(videoPath, filePath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.tvVideoLeftText.setText("00:00");
        mDataBinding.tvVideoRightText.setText("/" + TimeUtil.getMmss(videoLength));
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoLeftText.setText("00:00");
                mDataBinding.tvVideoRightText.setText("/" + TimeUtil.getMmss(videoLength));
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
                mp.seekTo(1);
                stopTime();
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.bf);
        mDataBinding.videoView.pause();
        stopTime();
    }
}